﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Linq;
using System.Linq;

namespace InvoiceInvoker.Logic.Repositories
{
	public class RegisteredCustomerRepository : InvoiceInvoker.Logic.RepositoryInterfaces.IRegisteredCustomerRepository
	{
		private string _connectionString;
		private int _registeredSellerId;

		public RegisteredCustomerRepository(int registeredSellerId)
		{
			_connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
			_registeredSellerId = registeredSellerId;
		}

		public List<RegisteredCustomer> GetAll()
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				var query = from customer in dataContext.RegisteredCustomers
							where customer.RegisteredSellerId == _registeredSellerId
							orderby customer.CompanyName ascending
							select customer;
				return query.ToList();
			}
		}

		public List<RegisteredCustomer> GetByName(string name)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				var query = from customer in dataContext.RegisteredCustomers
							where customer.RegisteredSellerId == _registeredSellerId &&
								  customer.CompanyName.StartsWith(name)
							orderby customer.CompanyName ascending
							select customer;
				return query.ToList();
			}
		}

		public List<RegisteredCustomer> GetByExpression(Func<RegisteredCustomer, bool> expression)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				var mainQuery = from customer in dataContext.RegisteredCustomers
								where customer.RegisteredSellerId == _registeredSellerId
								orderby customer.CompanyName ascending
								select customer;
				return mainQuery.Where(expression).ToList();
			}
		}

		public RegisteredCustomer GetById(int id)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				return dataContext.RegisteredCustomers.SingleOrDefault(customer => customer.Id == id);
			}
		}

		public void Add(RegisteredCustomer item)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				dataContext.RegisteredCustomers.InsertOnSubmit(item);
				dataContext.SubmitChanges();
			}
		}

		public void Remove(int itemId)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				var query = from customer in dataContext.RegisteredCustomers where customer.Id == itemId select customer;
				dataContext.RegisteredCustomers.DeleteOnSubmit(query.SingleOrDefault());
				dataContext.SubmitChanges();
			}
		}

		public void Update(RegisteredCustomer item)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				dataContext.RegisteredCustomers.Attach(item, GetById(item.Id));
				dataContext.SubmitChanges();
			}
		}
	}
}
